const express = require("express");

const router = express.Router();
const { user } = require("../models/model");
// 获取所有用户列表
router.get("/", async (req, res) => {
  try {
    const users = await user.find();
    res.send({
      code: 200,
      result: users,
    });
  } catch (error) {
    res.status(500).json({ message: "获取用户信息失败", error });
  }
});

// 获取单个用户
router.get("/userId", async (req, res) => {
  const { userId } = req.query;
  try {
    const use = await user.findById(userId).populate("friends");
    // console.log(use, "friends------------------------------");
    res.send({
      code: 200,
      result: use,
    });
  } catch (error) {
    console.log(error, userId);

    res.send({ message: "获取用户失败", error: error.message });
  }
});
// 添加好友
router.post("/addFriend", async (req, res) => {
  const { userId, friendId } = req.body;
  try {
    await user.findByIdAndUpdate(userId, {
      $addToSet: { friends: friendId }, // 使用 $addToSet 防止重复添加
    });
    res.send({ message: "好友添加成功" });
  } catch (error) {
    res.send({ message: "添加好友失败", error: error.message });
  }
});
module.exports = router;
